package cre.redis.thread;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
 * Created by CreGu on 2016/7/1.
 */
public class RedisLock {

    private Jedis jedis;
    private String[] lockedNames;

    public RedisLock() {
//        this.jedis = new Jedis("192.168.28.128");

        JedisPool jedisPool=new JedisPool("192.168.28.128");
        this.jedis=jedisPool.getResource();
    }

    public boolean lock(String name, int timeout, int expire, int interval) {

        long now = System.currentTimeMillis();
        long timeoutAt = now + timeout;
        long expireAt = now + expire;
        String lockKey = "Lock:" + name;
        while (true) {
            Long flag = jedis.setnx(lockKey, String.valueOf(expireAt));
            System.out.println(flag);
            if(flag==1){
//               获取锁成功，设置key的失效时间
                jedis.expire(lockKey, (int)expireAt);

                return true;
            }

            Long ttl = jedis.ttl(lockKey);
            if (ttl < 0) {
                jedis.set(lockKey, String.valueOf(expireAt));
                return true;
            }

            if (timeout <= 0 || timeoutAt < System.currentTimeMillis()) {
                break;
            }

            try {
                Thread.sleep(interval);
            } catch (InterruptedException e) {
                e.printStackTrace();
                return false;
            }
        }

        return false;
    }

    public boolean unlock(String name) {
        String lockKey = "Lock:" + name;
        jedis.del(lockKey);
        return false;
    }


}
